var mongoose= require('mongoose');
var Cate = require('../models/cate.model')

exports.create = function(req,res,next){
    var cate = new Cate(req.body);

    cate.save()
    .then(data=>{
        res.json(data);
    })
}

exports.update = function(req,res,next){
    
    var id = req.params.id; // req.param('id')
    // 现在操作的都是mongoose而不是mongodb
    Cate.findByIdAndUpdate(id,{$set: req.body}, {new:false} )
    .then(data=>{
        res.json({msg:'数据修改成功',status:200}); // 如果你要返回数据，这个data返回的是你之前修改的那个数据内容
    })
}

function reverseTree(data,pid){
    var result=[],temp;

    var data= JSON.parse(JSON.stringify(data));

    for(var i in data){
        if(data[i].parentId === pid){
            result.push(data[i]);

            temp = reverseTree(data,data[i]._id);
 
            if(temp.length>0){
                data[i].children = temp;
            }
        }
    }
    return result;
}

exports.getnewschildren = function(req,res,next){
    Cate.find({type:1},function(err,data){
        var children = filterChild(data,null);
        res.json(children);
    })  
}

function filterChild(data,pid){
    var result=[],temp;

    var data= JSON.parse(JSON.stringify(data));

    for(var i in data){
        if(data[i].parentId !== pid){
            result.push(data[i]);
            
        }
    }
    return result;
}


exports.list = function(req,res,next){
    var type= req.params.type;
    Cate.find({type:type},function(err,data){
        var rpTree = reverseTree(data,null);
        res.json(rpTree);
    })  
}

exports.newslist = function(req,res,next){
    var id= req.params.id;
    Cate.find({parentId:id},function(err,data){
        var rpTree = reverseTree(data,null);
        res.json(rpTree);
    })  
}

exports.remove = function(req,res,next){
    var id=req.params.id;
    var ids= [];

    Cate.findOne({_id:id},function(err,doc){
        if(doc){
            ids = [doc._id];

            doc.getChildren().then(function(docs){
                for(var i=0;i<docs.length;i++){
                    ids.push(docs[i]._id)
                } 

                Cate.remove({_id:{$in:ids}})
                .then(data=>{
                    res.json({"msg":"数据删除成功",status:200})
                })
            })


        }
    })
}